package com.cinema.servlet;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cinema.Bean.Hall;
import com.cinema.Bean.Movie;
import com.cinema.Bean.MovieSession;
import com.cinema.Bean.MsgStatistical;
import com.cinema.dao.IHallDao;
import com.cinema.dao.IMovieDao;
import com.cinema.dao.IMovieSessionDao;
import com.cinema.dao.imp.HallDaoMysql;
import com.cinema.dao.imp.MovieDaoMysql;
import com.cinema.dao.imp.MovieSessionDaoMysql;

public class MovieSessionServlet extends HttpServlet {
    
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
	
	IMovieSessionDao iMovieSessionDao = new MovieSessionDaoMysql();
	IMovieDao iMovieDao = new MovieDaoMysql();
	IHallDao iHallDao = new HallDaoMysql();
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		
		String method = request.getParameter("method");
		// 场次新增
		if ("add".equals(method)) {
			int insert = 0;
			
			String sessionId = request.getParameter("sessionId");
			String hallId = request.getParameter("hallId");
			String movieId = request.getParameter("movieId");
			String time = request.getParameter("time");
			double price = Double.parseDouble(request.getParameter("price"));
			
			MovieSession ms = new MovieSession();
			ms.setSessionId(sessionId);
			ms.setHallId(hallId);
			ms.setMovieId(movieId);
			ms.setTime(time);
			ms.setPrice(price);
			
			Boolean flag = compareTime(hallId,time); // 判断场次是否冲突, true为新增场次，false为失败
			
			if(flag) {
				insert = iMovieSessionDao.insert(ms);
			}
			
			if (insert == 1) {
				response.getWriter().print("success");
				request.getSession().removeAttribute("slist");
			}else {
				response.getWriter().print("error");
			}
			
		} else if("delete".equals(method)) {
			String sessionId = request.getParameter("sessionId");
			if (sessionId != null && sessionId != "") {
				
				MovieSession ms = new MovieSession();
				ms.setSessionId(sessionId);

				int delete = iMovieSessionDao.delete(ms);

				if (delete == 1) {
					response.getWriter().print("success"); 
					request.getSession().removeAttribute("slist");
				}else{
					response.getWriter().print("error");
				}
			}
		}else if("getMovieSession".equals(method)){
			String sessionId = request.getParameter("sessionId");
			
			if(sessionId!=null && sessionId!=""){
				// 场次信息
				MovieSession sessions = iMovieSessionDao.SelectById(sessionId);
				request.setAttribute("sessions", sessions);
				
				// 所有场厅
				List<Hall> HallList=iHallDao.selectAll();
				request.setAttribute("HallList", HallList);
				
				// 所有电影
				List<Movie> MovieList=iMovieDao.selectByWhere("movieStat !=3 ");
				request.setAttribute("MovieList", MovieList);
			}
			request.getRequestDispatcher("/Session/edit.jsp").forward(request, response);
			
		}else if("update".equals(method)){
			int update = 0;
			String sessionId = request.getParameter("sessionId");
			String hallId = request.getParameter("hallId");
			String movieId = request.getParameter("movieId");
			String time = request.getParameter("time");
			double price = Double.parseDouble(request.getParameter("price"));
			
			MovieSession ms = new MovieSession(sessionId,hallId,movieId,time,price);
			
			Boolean flag = compareTime(hallId,time); // 判断场次是否冲突, true为新增场次，false为失败
			if(flag) {
				update = iMovieSessionDao.update(ms);
			}
			
			if (update == 1) {
				response.getWriter().print("success");
				request.getSession().removeAttribute("slist");
			}else {
				response.getWriter().print("error");
			}
			
		}else if("select".equals(method)){
			request.getSession().removeAttribute("slist");
			String keyword=request.getParameter("keyword");
			
			List<MovieSession> ms=iMovieSessionDao.Select(keyword);
			request.getSession().setAttribute("slist", ms);
		}
	}

	/**
	 * 判断新增的场次是否和已有场次冲突
	 * @param hallId —— 场厅Id
	 * @param time —— 新增的场次时间
	 * @return flag —— true为新增场次，false为失败
	 */
	public boolean compareTime (String hallId,String time) {
		// 1. 查询最后的场次安排，场厅 = 当前选中的场厅
		MsgStatistical lastTime = iMovieSessionDao.selectByHallId("hallId = '"+ hallId +"'");
		
		SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		Boolean flag = false;
		
		try {
			long timeRelease;
			Integer intDuration;
			// 判断最后场次是否存在（即第一次新增）
			if(lastTime != null) {
				// 2. 场次放映时间毫秒
				timeRelease = dateFormat.parse(lastTime.getTime()).getTime();  
				// 3. 电影时长 + 间歇(10分钟清场) 
				intDuration = Integer.parseInt(lastTime.getCount()) + 10;
			}else {
				// 以当前时间为准
				timeRelease = new Date().getTime();
				intDuration = 10;
			}
			
			// 转化为毫秒
			long timeDuration = intDuration*60*1000 ;
			
			// 放映时间+间隔时间总和
			long timeSeconds = timeRelease + timeDuration;
			
			// 4.将当前新增的场次时间转化为毫秒
			long timeNew = dateFormat.parse(time).getTime();  
			
			if(timeNew > timeSeconds) { // 如果新增场次的时间大于最新的场次，则新增，否则，提示
				flag = true;
			} 
			
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return flag;
	}
	
}
